﻿using System.Collections.ObjectModel;
using System.Linq;
using GalaSoft.MvvmLight.Messaging;
using GalaSoft.MvvmLight.Threading;
using RTMBindings;
using RTMBindings.Responses;
using GalaSoft.MvvmLight.Command;
using System.Windows.Input;

namespace MilkCart.ViewModel
{
    public class TaskViewModel : ViewModel
    {
        public ICommand PostponeCommand { get; private set; }

        public ObservableCollection<RTMTaskSeries> Tasks { get; private set; }

        protected virtual string Filter { get; private set; }

        protected TaskViewModel()
        {
            Tasks = new ObservableCollection<RTMTaskSeries>();
            Messenger.Default.Register<NotificationMessage>(this, MessageReceived);

            PostponeCommand = new RelayCommand<int>(ExecutePostpone);
        }

        public void ExecutePostpone(int id)
        {
            if (Timeline == null)
                return; // TODO : Deal with this error


        }

        public TaskViewModel(string filter)
            : this()
        {
            Filter = filter;
        }

        protected virtual void MessageReceived(NotificationMessage msg)
        {
            switch (msg.Notification)
            {
                case NotificationMessages.UpdateMessage:
                    Update();
                    break;
            }
        }

        protected void Update()
        {
            if (Token == null)
                return;

            Messenger.Default.Send<NotificationMessage>(new NotificationMessage(NotificationMessages.StartedUpdating));
            RTMAuthBindings.CheckToken(MainPage.ApiKey, MainPage.Secret, Token, ContinueUpdate, ExecutionFailed);
        }

        protected virtual void ContinueUpdate(RTMGetTokenResponse response)
        {
            RTMTaskBindings.GetList(MainPage.ApiKey, MainPage.Secret, new RTMToken(response.Auth.Token), ContinueGetList,
                                    ExecutionFailed, filter: Filter);
        }

        private void ContinueGetList(RTMGetListResponse response)
        {
            DispatcherHelper.CheckBeginInvokeOnUI(() =>
            {
                Tasks.Clear();
                if (response.Tasks != null && response.Tasks.Lists != null)
                    foreach (var t in response.Tasks.Lists.Where(l => l != null && l.TaskSeries != null).SelectMany(tl => tl.TaskSeries).OrderBy(t => t.Task.Priority))
                        Tasks.Add(t);
            });
            Messenger.Default.Send<NotificationMessage>(new NotificationMessage(NotificationMessages.FinishedUpdating));
        }
    }
}
